layui.config({
    base: '../../layui/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
    formSelects: 'formSelects-v4'
}).use(['jquery', 'formSelects', 'form','layer','element'], function () {
    const form = layui.form
        , layer = layui.layer
        , element = layui.element
        , $ = layui.jquery;
    form.on('submit(save)', function (data) {
        const params = new FormData();
        params.append('postgresFile', $('#postgresFile')[0].files[0]);
        params.append('ids', data.field.ids);
        params.append('tempPath', data.field.tempPath);
        if (!$('#postgresFile')[0].files[0]) {
            layer.msg("请先上传postgres镜像文件", {icon: 2, time: 3000}, function () {
            })
            return
        }
        submit($, params);
        return false;
    });


    function submit($, params) {
        layer.msg("开始安装，请稍后...", {icon: 1, time: 10000}, function () {
        })
        $.ajax({
            url: '/admDb/installPostgres',
            type: 'POST',
            cache: false,
            processData: false,
            contentType: false,
            data: params,
            type: "POST",
            success: function (result) {

            }
        })
    }
    $("#close").on('click', function () {
        const index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    });
    //关闭页面
    function CloseWin() {
        parent.location.reload(); // 父页面刷新
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    }
    $("#postgresFile").on('change',function(){
        var curFile = this.files[0];
        $(".postgresSize").html(changeSize(curFile.size))
        $(".postgres").html(curFile.name)
    });
    $(function () {
        uploadStatus();
        uploadWebsocket()
    })

    function uploadStatus() {
        const dataJson = $("#dataJson").val()
        const data = JSON.parse(dataJson)
        $("#uploadList").html("")
        let html=""
        for (item of data){
            html+=" <fieldset class=\"layui-elem-field layui-field-title\" style=\"margin-top: 20px;\">\n" +
                "                <legend>"+item.ip+"</legend>\n" +
                "            </fieldset>\n" +
                "            <table class=\"layui-table\">\n" +
                "                <colgroup>\n" +
                "                    <col style=\"width: 200px\">\n" +
                "                    <col style=\"width: 100px\">\n" +
                "                    <col style=\"width: 150px\">\n" +
                "                    <col style=\"width: 250px\">\n" +
                "                </colgroup>\n" +
                "                <thead>\n" +
                "                <tr>\n" +
                "                    <th>文件名</th>\n" +
                "                    <th>大小</th>\n" +
                "                    <th>状态</th>\n" +
                "                    <th>上传进度</th>\n" +
                "                </tr>\n" +
                "                <tr id=\"postgres-" +item.id+"\">\n" +
                "                    <td class='postgres'></td>\n" +
                "                    <td class='postgresSize'></td>\n" +
                "                    <td>待上传</td>\n" +
                "                    <td>\n" +
                "                        <div class=\"layui-progress layui-progress-big\" lay-showpercent=\"true\"\n" +
                "                             lay-filter=\"progress-file-postgres-"+item.id+"\">\n" +
                "                            <div class=\"layui-progress-bar layui-btn-blue\" lay-percent=\"0%\"></div>\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </thead>\n" +
                "            </table>"
        }
        $("#uploadList").append(html)
    }

    //日志实时更新
    function uploadWebsocket() {
        //websocket对象
        let websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://" + sessionStorage.getItem('hostName') + "/websocket/logging");
        } else {
            console.error("不支持WebSocket");
        }
        //连接发生错误的回调方法
        websocket.onerror = function (e) {
            console.error("WebSocket连接发生错误", e);
        };
        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log("WebSocket连接成功")
        };
        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            //追加
            if (event.data) {
                let data = $.parseJSON(event.data);
                if (data.table == "dbInstall") {
                    if ("completeAll" == data.data) {
                        layer.msg("已全部安装完毕...", {icon: 1, time: 10000}, function () {
                        })
                    }
                    $("#uploadList").find("table tr").each(function () {
                        const id = $(this).attr("id")
                        if (!id) {
                            return
                        }
                        if (id.lastIndexOf("postgres-") != -1) {
                            const index = id.replace("postgres-", "")
                            const filename = $(this).find("td").eq(0).text();
                            if (filename == data.name) {
                                if (data.speedOfProgress != null && data.speedOfProgress != '') {
                                    element.progress('progress-file-postgres-' + index, data.speedOfProgress); //执行进度条。n 即为返回的进度百分比
                                }
                                let html = "";
                                if ("complete" == data.status) {
                                    html = "<span style='color: seagreen'>部署成功</span>"
                                }
                                if ("loading" == data.status) {
                                    html = "<span style='color: #760f8d'>加载镜像中</span>"
                                }
                                if ("starting" == data.status) {
                                    html = "<span style='color: #1a84d5'>正在启动postgres</span>"
                                }
                                if ("uploading" == data.status) {
                                    html = "<span style='color: #1a84d5'>uploading</span>"
                                }
                                $(this).find("td").eq(2).html(html);
                                element.render()
                            }
                        }

                        if (id.lastIndexOf("postgresWeb-") != -1) {
                            const index = id.replace("postgresWeb-", "")
                            const filename = $(this).find("td").eq(0).text();
                            if (filename == data.name) {
                                if (data.speedOfProgress != null && data.speedOfProgress != '') {
                                    element.progress('progress-file-postgresWeb-' + index, data.speedOfProgress); //执行进度条。n 即为返回的进度百分比
                                }
                                let html = "";
                                if ("complete" == data.status) {
                                    html = "<span style='color: seagreen'>部署成功</span>"
                                }
                                if ("loading" == data.status) {
                                    html = "<span style='color: #760f8d'>加载镜像中</span>"
                                }
                                if ("uploading" == data.status) {
                                    html = "<span style='color: #1a84d5'>uploading</span>"
                                }
                                $(this).find("td").eq(2).html(html);
                                element.render()
                            }
                        }

                    })
                }
            }
        };
        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log("WebSocket连接关闭")
        };
    }

});


